package com.rgs.oauth2gateway.web;

import com.rgs.oauth2gateway.feignClient.AuthTokenFeignClient;
import com.rgs.oauth2gateway.pojo.auth.AuthorizationDTO;
import com.rgs.oauth2gateway.pojo.r.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;

/**
 * @author RenGaoshuai
 * @date 2024/4/11 16:24
 * @description
 */

@RestController
@RequestMapping("/rgs/auth")
@Slf4j
public class TokenController {

    @Value("${token.scope:read}")
    private String scope;

    @Value("${token.grantType:client_credentials}")
    private String grantType;

    @Autowired
    private AuthTokenFeignClient authTokenFeignClient;


   //gateway获取token
    @PostMapping("/getToken")
    public Result<String> token(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders httpHeaders = request.getHeaders();
        String account = httpHeaders.getFirst("Account"); // 账户信息

        if (StringUtils.isBlank(account)) {
            return Result.fail("账户信息不能为空！");
        }
        String accessToken;
        try {
            String authorization = "Basic " + account;
            AuthorizationDTO authorizationDTO = authTokenFeignClient.getToken(scope,grantType,authorization);
            if (authorizationDTO == null || StringUtils.isBlank(authorizationDTO.getAccess_token())) {
                return Result.fail("获取token异常，请稍后重试！");
            }
            accessToken = authorizationDTO.getAccess_token();
        }catch (Exception e) {
            return Result.fail("获取token失败，请检查账户信息是否有误！");
        }
        return Result.success(accessToken);
    }


}
